<?php
class IndexAction extends MemberAction{
	public $db;
	public $userinfo;
	public function _initialize(){
		parent::_initialize();
		$this->db=D('Member');
 		$this->userinfo = $this->db->alias('m')->where(array('m.id'=>$this->memberInfo['id'],'m.site_id'=>__RELATEID__))->Field("m.*")->find();
	}
	public function index(){
        $this->levelnum=D('Member')->where('id = '.$this->memberInfo['id'])->getField('level');
		//父级信息
		$parent_info = $this->db -> where(array('id' => $this->memberInfo['pid'])) -> find();
		$this -> assign('parent_info', $parent_info);
		$this -> assign('userinfo', $this->userinfo);
		$this->LevelName = $this->db -> getLevelName($this->userinfo['id']);
		$this->mylevel=$this->db->where('id = '.$this->userinfo['id'])->getfield('level');
		if($this->mylevel == 1){
		    $this->myshop=D('Supplier')->where('member_id = '.$this->memberInfo['id'])->getfield('id');
        }
		$this->cperformance();//会员业绩统计
		$this->countdetail();//待提现统计
//		$this->integrals();//积分
		$affobj = array();
		//我自己的消费总额
		$this->mySaleTotal = M('Sale') -> where(array('pay_status' => 1, 'member_id' => $this->memberInfo['id'])) -> sum('total');
		//调用分成类显示分成数据
		$affobj = $payment = M('Affiliatesetting') -> where(array('site_id' => __SITEID__, 'status' => 1)) -> find();
		if($affobj){
			import("@.ORG.Affiliate.".$affobj['classname']);
			$class = $affobj['classname'];
			$Threelevel = new $class(0,__RELATEID__,$this->userinfo['id']);
			$affdata = $Threelevel -> getAffData();//dump($affdata);
		}
		if(D('Faker')->where('id = 1')->getfield('status')==1){
			$this->allTotal=D('Faker')->where('id = 1')->getfield('money');
			$this->memberLevelOne=D('Faker')->where('id = 1')->getfield('member');
			$this->yesterday=D('Faker')->where('id = 1')->getfield('sixth');
		}else{
			$this->allTotal=D('Sale')->where('pay_status = 1')->sum('total');//平台总收益
			$this->memberLevelOne=M('Supplier') -> where(1) -> count();//平台总商家

			$ystart = mktime(0, 0 , 0,date("m"),date("d"),date("Y"))-86400;
			$yend = mktime(23,59,59,date("m"),date("d"),date("Y"))-86400;
			$this->yesterday=M('Sale') -> where(array('member_id'=>$this->memberInfo['id'],'pay_status' => 1,'create_time'=>array('between',array($ystart,$yend)))) -> sum('total');
		}
        $this->fumoshang=D('Member')->where('level = 6')->count();
        $this->daily=D('Member')->where('level = 4')->count();
        $mylevel=D('Member')->where('id = '.$this->memberInfo['id'])->getfield('level');
		$Model = M();
		$this->totalMember =count($Model->query("SELECT DISTINCT smember_id FROM `think_member_member` where deep < 3 and   member_id = ".$this->memberInfo['id']." and ( level = 0  or level = 1 or level = ".$mylevel.")"));

		//关联的供货商
		$supplier = M('Supplier') -> where(array('member_id' => $this->memberInfo['id'], 'type' => 2, 'status' => 1)) -> find();
		
		$this->assign('supplier', $supplier);
		
		$this->serviceCard = M('Servicecard') -> where(array('site_id' => __SITEID__)) -> count();
		$this->assign('affdata', $affdata);
		$this->myAdminUser = M('User') -> where(array('member_id' => $this->memberInfo['id'])) -> find();
		//积分
 		$this->display();
	}
	//登录用户关联的管理后台
	public function manage(){
		if(isset($_GET['anonymous']) && intval($_GET['anonymous']) > 0){
			session('anonymous', intval($_GET['anonymous']));
		}
		if(isset($_GET['jump'])){
			$url = $_GET['jump'];
		}else{
			$url = '/Admin';
		}
		redirect($url);
	}
    public function aff(){
		C('URL_MODEL', 0);
		$this->display();
	}
	//用户修改资料
	public function edit(){
		if(isset($_POST['edit'])){
			$db = D('Member');
			
			if(false !== $db->where(array('id' => $this->userinfo['id']))->save($_POST)){
				$this->success('修改成功');
			}else{
				$this->error($db->getError());
			}
			exit();
		}
		$this->assign('info',$this->userinfo);
	
		$this->display();
	}
	//上传头像
	public function upload(){
		import('ORG.Net.UploadFile');
		$upload = new UploadFile();// 实例化上传类
		$upload->maxSize  = 100*1024;// 设置附件上传大小
		$upload->allowExts  = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
		$upload->savePath =  './Public/Uploads/';// 设置附件上传目录
		
	
		if(!$upload->upload()) {// 上传错误提示错误信息
		   $this->error($upload->getErrorMsg());
		}else{// 上传成功 获取上传文件信息
		   $info = $upload->getUploadFileInfo();
		}
    }
	//跳转到会员开通的最后一个站点
	public function sitelast(){
//		var_dump($this->memberInfo['id']);
		//找到这个站点
		$site = M('Site') -> where(array('member_id' => $this -> memberInfo['id'])) -> order('id desc') -> find();
		if($site){
			//找到了
			redirect('/'.$site['id']);
	    }
	}
	//个人资料
	public function head(){
		$id = $this-> memberInfo['id'];
		if(IS_POST){
			$id=$this->memberInfo['id'];
			//$src=$this->db->where("member_id= $id")->getField('img_url');
			$src='.'.$_POST['img_url'] = $_POST['src'];
			$bigsrc = pathinfo($src, PATHINFO_DIRNAME).'/thumb_'.pathinfo($src, PATHINFO_FILENAME).'.'.pathinfo($src, PATHINFO_EXTENSION);
			$images=getimagesize($bigsrc);
			//$targ_w = $targ_h=540;
			$targ_w=$this->_post('w');
			$targ_h=$this->_post('h');
			$jpeg_quality=100;
			$img_r = imagecreatefromjpeg($src);
			//保存原图
			imagejpeg($img_r,$bigsrc,$jpeg_quality);
			$dst_r = ImageCreateTrueColor( $targ_w, $targ_h );
			imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],
			$targ_w,$targ_h,$_POST['w'],$_POST['h']);
			imagejpeg($dst_r,$src,$jpeg_quality);
			//dump( $dst_r );
			$data['img_url'] = $_POST['img_url'];
			$map['id'] = $id;
			$ret = $this->db -> where($map) -> save($data);
			if($ret !== false){
				$memberInfo = session('memberInfo');
				$memberInfo['img_url'] = $_POST['img_url'];
				session('memberInfo', $memberInfo);
				$this->success('修改成功');
			}else{
				$this->error($this->db -> getError());
			}
		}
		$this -> display();
	}
	public function userlistadv(){
		$id = $map['mm.member_id'] = isset($_GET['member_id']) ? intval($_GET['member_id']) : $this->memberInfo['id'];
	    //商家数
		$this -> bc = M('Member_member') -> where(array('member_id' => $id, 'level' => 1,'deep'=>1)) -> count();
		$this -> sc = M('Member_member') -> where(array('member_id' => $id, 'level' => 6,'deep'=>array('elt', 2))) -> count();
		$this -> ec = M('Member_member') -> where(array('member_id' => $id, 'level' => 5,'deep'=>1)) -> count();
		$this -> mc = M('Member_member') -> where(array('member_id' => $id, 'level' => 0,'deep'=>array('elt', 2))) -> count();
		$this->initView();
        $map['mm.level'] = isset($_GET['level']) ? intval($_GET['level']) : 1;
		if(isset($_GET['level'])&&($_GET['level']==0||$_GET['level']==6)){
			$this->lemonTree=1;
		}elseif($_GET['level']==1){
			$this->lemonTree=2;
		}
		$db = D('Member_member');
		$this -> level = $map['mm.level'];
		if($map['mm.level']==1||$map['mm.level']==5){
			$map['mm.deep']=1;
		}else{
			$map['mm.deep']=array('elt',2);
		}
		if(isset($_GET['keywords']) && ($_GET['keywords']) !=''){
			$map['m.nickname'] = array('like', '%'.$_GET['keywords'].'%');
		}
		//dump($map);
		$db -> _list($this->view, $map, 'mm.deep');
		//echo $db -> getLastSql();
//		var_dump(D('Member_member')->getLastSql());
		$this -> display();
		
	}
	public function deeplist(){
	    if($_GET['id']){
	        $id=$_GET['id'];
	        $this->membername=D('Member')->where('id = '.$id)->getfield('nickname');
            $this -> bc = M('Member_member') -> where(array('member_id' => $id, 'level' => 1,'deep'=>1)) -> count();
            $this->initView();
            $map['mm.level'] = 1;
            $db = D('Member_member');
            $this -> level = 1;
            $map['mm.deep']=1;
            $map['member_id']=$id;
            if(isset($_GET['keywords']) && ($_GET['keywords']) !=''){
                $map['m.nickname'] = array('like', '%'.$_GET['keywords'].'%');
            }
            $db -> _list($this->view, $map, 'mm.deep');
            $this->display();
        }
    }
	public function userCount(){
		
		
		$memberInfo=$_SESSION['memberInfo'];
		
		 $timek = mktime(0, 0 , 0,date("m"),date("d"),date("Y"))-86400;
        $timej = mktime(23,59,59,date("m"),date("d"),date("Y"))-86400;
        $cashwhere['dateline'] = array(array('gt',$timek),array('lt',$timej));
		$cashwhere['member_id']=array('eq',$memberInfo['id']);
		$cashwhere['pdstate']=array('gt',0);
		$cashwhere['mem_brankid']=array('eq',0);
		
        $this->yesterdayCash=D('Member_account_log')->where($cashwhere)->Sum('changenum');
		if($this->yesterdayCash){
		echo $this->yesterdayCash;	
		exit();
		}
		echo 0;
		
	}
	//会员统计列表
	public function userlist(){
		$id = $map['mm.member_id'] = isset($_GET['member_id']) ? intval($_GET['member_id']) : $this->memberInfo['id'];
        $map['mm.level'] = 0;
		$this->initView();
		$db = D('Member_member');
		if(isset($_GET['keywords']) && ($_GET['keywords']) !=''){
			$map['m.nickname'] = array('like', '%'.$_GET['keywords'].'%');
		}
		$db -> _list($this->view, $map, 'mm.deep');
		$this -> display();
	}
	//会员统计列表
	public function userlistadv1(){
		//市场人数统计
		$datacount[0] = $this->db -> getLevel1Count($this->memberInfo['id'], 1, 1);
		//计算八级以内市场人数
		$datacount[1] = $this->db -> getLevel1Count($this->memberInfo['id'], 1, 100);
		//echo $this->db -> getLastSql();
		$this->datacount = $datacount;
		//dump($datacount);
		$id = $map['mm.member_id'] = $this->memberInfo['id'];
		$this->initView();
		$db = D('Member_member');
		//VIP数量
		$map['mm.deep'] = array('elt', 100);
		if(isset($_GET['deep']) && intval($_GET['deep']) > 0){
			$map['mm.deep'] = intval($_GET['deep']);
		}
		$map['mm.level'] = array('egt', 1);
		$db -> _list($this->view, $map, 'mm.deep');
		$this -> display();
	}
	//会员业绩统计
	public function cperformance(){
	  $account_log = M('Member_account_log');
	  //获取时间区间
	  $timek = mktime(0, 0 , 0,date("m"),1,date("Y"));
      $timej = mktime(23,59,59,date("m"),date("t"),date("Y"));
	  //设置查询条件
	  $map['member_id'] = $this->memberInfo['id'];
	 //$map['dateline'] = array(array('gt',$timek),array('lt',$timej));//按月
	  $map['order_id'] = array('gt',0);
	  $zperSql = $account_log->where($map) -> Field('distinct order_id, product_id, attr, goodsMoney') -> buildSql();
	  $zper = $account_log->table($zperSql.' a') -> Sum('goodsMoney');//总业绩
	  //if(isset($_GET['zper'])){echo $account_log -> getLastSql();}
	  $this -> assign('zper', $zper);
	  $orderinfo = $account_log->table($zperSql.' a')->count();  //本月总订单
	  $this -> assign('orderinfo', $orderinfo);
      $map['member_id'] = $this->memberInfo['id'];
      $map['order_id'] = array('GT','0');
	  $map['pdstate'] = array('GT','1');
	  $map['hbstatus'] = 0;
	  $commission = $account_log->where($map)->Sum('changenum'); //本月总佣金（营业收益）
	 if(D('Member')->where('id = '.$this->memberInfo['id'])->getfield('level') == 1){//推荐收益
		 $newmap1['member_id'] = $this->memberInfo['id'];
		 $newmap1['types']=1;
		 $newmap1['order_id'] = array('GT','0');
		 $commission1 = $account_log->where($newmap1)->Sum('changenum'); //本月总佣金
		 $commission=$commission+$commission1;
	 }
    $map['dateline'] = array(array('gt',mktime(0, 0 , 0,date("m"),date('d'),date("Y"))-86401),array('lt',mktime(0, 0 , 0,date("m"),date('d'),date("Y"))));//昨天
	 $this->yestercom=$account_log->where($map)->Sum('changenum');
        $this -> assign('commission', $commission);
	}
	//获取待提现统计
	public function countdetail(){
	   $account_log = M('member_account_log');
	   $map['member_id'] = $this->memberInfo['id'];
	   $map['pdstate'] = array('eq',2);
	   $map['status'] = array('eq',0);
	   $dnum = $account_log->where($map)->Sum('changenum');
	   $this->assign('dnum',$dnum);
	}
  //积分统计
  public function integrals(){
	  //初始化积分
	 $id = $this->memberInfo['id'];
	 import("@.ORG.Integrals.Integral");
	 $Integral = new Integral($id);
	 $integral_number = $Integral->getIntegral();
     $this->assign('integrals',$integral_number);
  }
  //互转积分
  public function tochange(){
     $id = $this->memberInfo['id'];
	 $toid = $this->_post('toid');
	 if(IS_POST){
		if($this->_post('integrals') && $this->_post('money')){
		   $this->error('不能同时互转资金和积分');
		}
	   if($this->_post('integrals')){
			 $integrals = $this->_post('integrals');
			 $typelist = M('Integral_type') -> where(array('site_id' => __SITEID__)) -> select();
			foreach($typelist as $k => $v){
				import("@.ORG.Integrals.".$v['typename']);
				$class = $v['typename'];
				$integral = new $class($id);
				$integral_adjustIntegral = $integral->adjustIntegral($id, $toid, $integrals);
				//dump($integral_adjustIntegral);exit;
			   if($integral_adjustIntegral){
			     $this->success('操作成功');
				 exit;
			   }
			}
			$this->error('积分不足');
			exit;
	   }
	   if($this->_post('money')){
	        $money = $this->_post('money');
			$typelist = M('Integral_type') -> where(array('site_id' => __SITEID__)) -> select();
			foreach($typelist as $k => $v){
				import("@.ORG.Integrals.".$v['typename']);
				$class = $v['typename'];
				$integral = new $class($id);
				$integral_adjustMoney = $integral->adjustMoney($id, $toid, $money);
			   if($integral_adjustMoney){
			     $this->success('操作成功');
				 exit;
			   }
			}
			$this->error('资金不足');
			exit;
	   }
	 }
	 $this->assign('toid',$this->_get('id'));
	 $integral_logDB = M('integral_log');
	 $list = $integral_logDB->where(array('member_id'=>$id))->select();
	 $this->assign('list',$list);
	 $memberDB = M('member');
	 $integral_numberDB = M('integral_number');
	 $typelist = M('Integral_type') -> where(array('site_id' => __SITEID__)) -> select();
			foreach($typelist as $k => $v){
				import("@.ORG.Integrals.".$v['typename']);
				$class = $v['typename'];
				$integral = new $class($id);
				$integral_judgeIntegral = $integral->judgeIntegral();
			   if($integral_judgeIntegral){
				 $integral_number = $integral_numberDB->where(array('member_id'=>$id,'typename'=>$v['typename']))->find();
			     $judgeIntegral = 1;
			   }
	  }
	 $member = $memberDB->where(array('id'=>$id))->find();
	 $this -> assign('Integral', $integral_number['number']);
	 $this -> assign('money', $member['money']);
	 $this->display();
  }
  //服务卡券
  public function serviceCard(){
	 $db = D('Servicecard');
	 $this->initView();
	 $map['site_id'] = __SITEID__;
	 $map['member_id'] = $this->memberInfo['id'];
	 $db -> _list($this->view, $map);
	 $this->display();
  }
  //服务卡券
  public function servicelog(){
	 $db = D('Serviceclog');
	 if(isset($_POST['Serviceclog_id'])){
		$Serviceclog_id = intval($_POST['Serviceclog_id']);
		$ret = $db -> where(array('id' => $Serviceclog_id, 'member_id' => $this->memberInfo['id'], 'status' => 0)) -> data(array('usetime' => time(), 'status' => 1)) -> save();
		if($ret){
			$this->success('确认成功');
		}else{
			$this->error($db -> getError());
		}
		exit;
	 }
	 $this->list = $db -> where(array('servicecard_id' => $this->_get('servicecard_id'), 'member_id' => $this->memberInfo['id'], 'status' => 1)) -> select();
	 $this -> info = $db -> where(array('servicecard_id' => $this->_get('servicecard_id'), 'member_id' => $this->memberInfo['id'], 'status' => 0)) -> find();
	 $this->count = $db -> where(array('servicecard_id' => $this->_get('servicecard_id'), 'member_id' => $this->memberInfo['id'], 'status' => 0)) -> count();
	 $this->display();
  }
  //使用服务卡
	
	
	
	//显示商家二维码
	public function productqr(){
		//查询供货商
		$map['member_id'] = $this-> memberInfo['id'];
		$supplier = M('Supplier') -> where($map) -> select();
		foreach($supplier as $k => $v){
			D('Supplier') -> createqr($v['id']);
		}
		//查询二维商品
		$this->list = M('Product') -> where(array('supplier_id' => $supplier[0]['id'], 'status' => -1)) -> select();
		$this->display();
	}
	public function service(){
		$pagesize= 10;
		$map='level = 6 and number like "F80%"';
		$count=D('Member')->where($map)->count();
		import ( 'ORG.Util.Page' );
		$p=new Page($count,$pagesize);
		$this->list=D('Member')->where($map)->limit($p->firstRow.','.$p->listRows)->order('number')->select();
		$this->pages = $p->show();
		$this->display();
	}
	public function Daily(){
        $pagesize= 10;
        $map='level = 4 ';
        $count=D('Member')->where($map)->count();
        import ( 'ORG.Util.Page' );
        $p=new Page($count,$pagesize);
        $this->list=D('Member')->where($map)->limit($p->firstRow.','.$p->listRows)->order('number')->select();
        $this->pages = $p->show();
        $this->display();
    }
	public function myArea(){
	    //我的区域
		if($this->memberInfo['area']!=0){
			$county=D('Region')->where('region_id = '.$this->memberInfo['area'])->getfield('region_name');
			$father_id=D('Region')->where('region_id = '.$this->memberInfo['area'])->getfield('father_id');
			$city=D('Region')->where('region_id = '.$father_id)->field('region_name,father_id')->select();
			$province=D('Region')->where('region_id = '.$city[0]['father_id'])->getfield('region_name');
			$this->area=$province.','.$city[0]['region_name'].','.$county;
			//区域商家数
			$this->totalSupplier=0;
			//商家总营业额
//		(32,35,41,60,89,110,902,1316,1771,604)
			$supplier=D('Supplier')->where('area like "%,'.$this->memberInfo['area'].',%" and type = 2 ')->getfield('id',true);
		   
			$this->total=0;
			foreach($supplier as $k =>$v){
				$supplier_.=','.$v;
				$this->totalSupplier++;
			}
		
			$supplier_=substr($supplier_,1);
			if($this->memberInfo['uplevel_time']!=0){
			$this->total+=D('Order')->alias('o')->where('s.supplier_id in ('.$supplier_.') and s.pay_status = 1 and s.create_time >  '.$this->memberInfo['uplevel_time'])->join('left join `think_sale` as s on o.id=s.order_id  ')->sum('o.total');
		}else{
			$this->total=0;	
		}
		}
		
	    //我的收益
		if($this->memberInfo['uplevel_time']!=0){
        $this->mymoney=D('Member_account_log')->where('member_id = '.$this->memberInfo['id'].' and status =1 and types = 2 and dateline > '.$this->memberInfo['uplevel_time'])->sum('changenum');
		}else{
		$this->mymoney=0;
		}
//        $this->mymoney=D('Member_account_log')->where('id = '.$this->memberInfo['id'].' and pdstate = 3')->sum('changenum');
	    $this->display();
    }
}